﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using Zero.UControl.Base;
using Zero.UControl.Base.Models;

namespace Zero.UControl.Component
{
    /// <summary>
    /// FileUpload.xaml 的交互逻辑
    /// </summary>
    public partial class FileUpload : UserControl
    {
        public FileUpload()
        {
            InitializeComponent();
            FileList.Add(new UploadBoxItem(string.Empty));
        }

        public bool AllowMulti { get; set; }
        public ObservableCollection<UploadItem> FileList { get; set; } = new ObservableCollection<UploadItem>();

        #region 依赖属性
        public Func<ObservableCollection<UploadItem>, Response> ProcessUpload
        {
            get { return (Func<ObservableCollection<UploadItem>, Response>)GetValue(ProcessUploadProperty); }
            set { SetValue(ProcessUploadProperty, value); }
        }

        public static readonly DependencyProperty ProcessUploadProperty =
            DependencyProperty.Register("ProcessUpload", typeof(Func<ObservableCollection<UploadItem>, Response>), typeof(FileUpload));


        public Action<Response> SuccessHandle
        {
            get { return (Action<Response>)GetValue(SuccessHandleProperty); }
            set { SetValue(SuccessHandleProperty, value); }
        }

        public static readonly DependencyProperty SuccessHandleProperty =
            DependencyProperty.Register("SuccessHandle", typeof(Action<Response>), typeof(FileUpload));


        public Action<Response> FailHandle
        {
            get { return (Action<Response>)GetValue(FailHandleProperty); }
            set { SetValue(FailHandleProperty, value); }
        }

        public static readonly DependencyProperty FailHandleProperty =
            DependencyProperty.Register("FailHandle", typeof(Action<Response>), typeof(FileUpload));

        public UploadMode UploadMode
        {
            get { return (UploadMode)GetValue(UploadModeProperty); }
            set { SetValue(UploadModeProperty, value); }
        }

        public static readonly DependencyProperty UploadModeProperty =
            DependencyProperty.Register("UploadMode", typeof(UploadMode), typeof(FileUpload), new PropertyMetadata(UploadMode.Single, OnPropertyChanged));
        #endregion

        #region 事件方法

        private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var fileupload = (d as FileUpload);
            if (e.Property.Name == "UploadMode")
            {
                fileupload.AllowMulti = Enum.Parse<UploadMode>(e.NewValue.ToString()) == UploadMode.Single ? false : true;
            }
        }


        private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "图片文件|*.jpg;*.png;*.gif";
            openFileDialog.Title = "请选择要上传的图片文件";
            openFileDialog.Multiselect = AllowMulti;

            bool? flag = openFileDialog.ShowDialog();
            if (flag != null && flag == false) return;

            string[] fileNames = openFileDialog.FileNames;
            foreach (string fileName in fileNames)
            {
                if (File.Exists(fileName))
                {
                    if (UploadMode == UploadMode.Single)
                    {
                        FileList.Clear();
                        FileList.Add(new FileItem(fileName));
                        var boxItem = FileList.FirstOrDefault(f => f.GetType() == typeof(UploadBoxItem));
                        if (boxItem == null) return;
                        FileList.Remove(boxItem);
                    }
                    else if (UploadMode == UploadMode.Multiple)
                    {
                        FileList.Add(new FileItem(fileName));
                    }
                }
            }

            // 处理文件上传
            Response? response = ProcessUpload?.Invoke(FileList);
            if (response == null) return;

            if (response.StatusCode == 200)
            {
                SuccessHandle?.Invoke(response);
            }
            else
            {
                FailHandle?.Invoke(response);
            }
        }

        private void ImageToolBox_Delete(object sender, RoutedEventArgs e)
        {
            var imgBox = sender as ImageToolBox;
            if (imgBox == null) return;

            string absoluteUri = imgBox.UrlSource.UriSource.AbsoluteUri;
            string filePath = string.Empty;
            if (absoluteUri.StartsWith("http", StringComparison.OrdinalIgnoreCase) || absoluteUri.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                filePath = absoluteUri;
            }
            else if (absoluteUri.StartsWith("file", StringComparison.OrdinalIgnoreCase))
            {
                filePath = new Uri(absoluteUri).LocalPath;
            }
            var fileItem = FileList.FirstOrDefault(f => f.UrlPath == filePath);
            if (fileItem == null) return;

            FileList.Remove(fileItem);
            if (UploadMode == UploadMode.Single && FileList.Count == 0)
            {
                FileList.Add(new UploadBoxItem(string.Empty));
            }
        }
        #endregion

    }

    public enum UploadMode
    {
        Single,
        Multiple
    }
}
